package cn.lhl01.sys.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.lhl01.common.Results;
import cn.lhl01.sys.entity.po.SysUser;
import cn.lhl01.sys.mapper.SysUserMapper;
import cn.lhl01.sys.service.SysUserService;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Jwts;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lhl
 * @since 2023-02-08
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImp extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

	@NonNull
	private PasswordEncoder passwordEncoder;
	@NonNull
	private RedisTemplate redisTemplate;

	@Override
	public Results login(String uniqueIdentification, String password) {

		if (!NumberUtil.isNumber(uniqueIdentification)) {
			//不是数字
			return Results.paramError("用户编号不存在");
		}

		SysUser one = this.getById(NumberUtil.parseLong(uniqueIdentification));

		if (null == one) {
			//查不到
			return Results.paramError("用户编号不存在");
		}

		//String encode = passwordEncoder.encode(password);
		//验证密码true正确 false不正确
		if (!passwordEncoder.matches(password, one.getPassword())) {
			return Results.paramError("密码不正确");
		}

		long userId = one.getId();
		//redisTemplate.opsForValue().get(userId);

		JSONObject json = new JSONObject();
		json.put("userId", userId);

		long nowTime = System.currentTimeMillis();

		String token = Jwts.builder()
				.setHeaderParam("alg", "HS256")
				.setHeaderParam("typ", "JWT")
				.setSubject("JWT")
				.setIssuer(String.valueOf(userId))
				.setExpiration(new Date(nowTime + Results.EXPIRE_TIME)) // 过期时间
				.claim("userId", userId) //添加自定义的key和value 信息
				.claim("userInfo", json) //添加自定义的key和value 信息
				.signWith(Results.SECRET_KEY) // 使用secretKey进行签名
				.compact(); // 生成JWT字符串

		redisTemplate.opsForValue().set(userId, token, 1000 * 60 * 60 * 24, TimeUnit.MILLISECONDS);

		Object data = token;
		return Results.success(data);
	}

	@Override
	public SysUser selectByidWithAuthority(Long id) {
		return this.baseMapper.selectByidWithAuthority(id);
	}
}
